package com.atguigu.realtime.app.dws;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.bean.CourseCommentBean;
import com.atguigu.realtime.utils.*;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

public class DwsCourseUserComment {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
       // StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // TODO 2 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */

        //todo 3 从kafka读取 dwd_interaction_comment
        String topicName = "dwd_interaction_comment";
        String GroupID = "dws_course_user_comment";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, GroupID));

        //todo 4 转换结构
        SingleOutputStreamOperator<CourseCommentBean> mapStream = streamSource.map(new MapFunction<String, CourseCommentBean>() {
            @Override
            public CourseCommentBean map(String value) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                return CourseCommentBean.builder()
                        .course_id(jsonObject.getString("course_id"))
                        .user_id(jsonObject.getString("user_id"))
                        .review_stars(Integer.parseInt(jsonObject.getString("review_stars")))
                        .review_level(jsonObject.getString("review_level"))
                        .ts(jsonObject.getLong("ts"))
                        .build();
            }
        });

        //todo 5设置commentUserCt值

        SingleOutputStreamOperator<CourseCommentBean> processStream
                = mapStream.keyBy(CourseCommentBean::getUser_id)
                .process(new KeyedProcessFunction<String, CourseCommentBean, CourseCommentBean>() {
                    private ValueState<String> lastDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        // 此状态每个用户每天最后一次评价日期
                        lastDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastDateState", String.class));
                    }

                    @Override
                    public void processElement(
                            CourseCommentBean bean,
                            Context ctx,
                            Collector<CourseCommentBean> collector) throws Exception {

                        String lastDate = lastDateState.value();
                        String today = DateFormatUtil.toDate(bean.getTs() * 1000);

                        Long commentUserCt = 0L;
                        if (!today.equals(lastDate)) {
                            // 跨天
                            commentUserCt = 1L;

                            lastDateState.update(today);

                            bean.setCommentUserCt(commentUserCt);
                        }

                        Long goodCommentUserCt = 0L;
                        if ("五星好评".equals(bean.getReview_level())) {
                            goodCommentUserCt = 1L;

                            bean.setGoodCommentUserCt(goodCommentUserCt);
                        }

                        collector.collect(bean);
                    }
                });

        //todo 6 分组开窗聚合
        SingleOutputStreamOperator<CourseCommentBean> watermarks = processStream.assignTimestampsAndWatermarks(WatermarkStrategy
                .<CourseCommentBean>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                .withTimestampAssigner(new SerializableTimestampAssigner<CourseCommentBean>() {
                    @Override
                    public long extractTimestamp(CourseCommentBean element, long recordTimestamp) {
                        return element.getTs() * 1000;
                    }
                }));
        SingleOutputStreamOperator<CourseCommentBean> reduceStream = watermarks.keyBy(CourseCommentBean::getCourse_id)
                .window(TumblingEventTimeWindows.of(Time.seconds(10L)))
                .reduce(new ReduceFunction<CourseCommentBean>() {
                    @Override
                    public CourseCommentBean reduce(CourseCommentBean value1, CourseCommentBean value2) throws Exception {
                        value1.setCommentUserCt(value1.getCommentUserCt() + value2.getCommentUserCt());
                        value1.setGoodCommentUserCt(value1.getGoodCommentUserCt() + value2.getGoodCommentUserCt());
                        value1.setReview_stars(value1.getReview_stars() + value2.getReview_stars());

                        return value1;
                    }
                }, new WindowFunction<CourseCommentBean, CourseCommentBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<CourseCommentBean> input, Collector<CourseCommentBean> out) throws Exception {
                        CourseCommentBean bean = input.iterator().next();
                        bean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        bean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));

                        bean.setGoodRat(bean.getGoodCommentUserCt() * 1.0 / (bean.getCommentUserCt()==0?bean.getGoodCommentUserCt():bean.getCommentUserCt()));

                        bean.setUserAvgStars(bean.getCommentUserCt() * 1.0 / (bean.getReview_stars()==0?bean.getCommentUserCt():bean.getReview_stars()) );

                        bean.setTs(System.currentTimeMillis());

                        out.collect(bean);
                    }
                });
        //todo 7 关联 dim 表
        //dim_course_info
        SingleOutputStreamOperator<CourseCommentBean> resultStream = reduceStream.map(new RichMapFunction<CourseCommentBean, CourseCommentBean>() {
            DruidDataSource dataSource = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                dataSource = DruidPhoenixDSUtil.getDataSource();
            }

            @Override
            public CourseCommentBean map(CourseCommentBean value) throws Exception {
                List<JSONObject> testPaper = DimUtil.getDimInfo(dataSource.getConnection(), "DIM_COURSE_INFO", value.getCourse_id());
                if (testPaper.size() > 0) {
                    JSONObject tp = testPaper.get(0);
                    value.setCourseName(tp.getString("courseName"));

                }
                return value;
            }
        });

        resultStream.print();

        //写入到click house
        resultStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_course_user_comment values(?,?,?,?,?,?,?,?)"));


        //执行
        env.execute(GroupID);


    }
}
